package cn.tedu.tcc;

import cn.tedu.entity.Order;
import cn.tedu.mapper.OrderMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Component
public class OrderTccActionImpl implements OrderTccAction {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    @Transactional
    public boolean prepare(BusinessActionContext ctx, Long orderId, Long userId, Long productId, Integer count, BigDecimal money) {
        orderMapper.create(new Order(orderId,userId,productId,count,money,0));
        //第一阶段添加标记
        ResultHolder.setResult(OrderTccAction.class, ctx.getXid(), "p");
        return true;
    }

    @Override
    @Transactional
    public boolean commit(BusinessActionContext ctx) {
        /**
         * ctx 对象先变成json,再向第二阶段传递,会丢失类型信息
         * 取出的orderId 可能是 Integer 或者 Long 类型
         * 从上下文对象取出orderId
         */
        if (ResultHolder.getResult(OrderTccAction.class, ctx.getXid()) == null){
            return true;
        }
        Long orderId = Long.valueOf(ctx.getActionContext("orderId").toString());
        orderMapper.updateStatus(orderId, 1);
        ResultHolder.removeResult(OrderTccAction.class, ctx.getXid());
        return true;
    }

    @Override
    @Transactional
    public boolean rollback(BusinessActionContext ctx) {
        Long orderId = Long.valueOf(ctx.getActionContext("orderId").toString());
        orderMapper.deleteById(orderId);
        return true;
    }
}
